package com.hanqian.kepler.web.controller.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hanqian.kepler.common.bean.jqgrid.JqGridFilter;
import com.hanqian.kepler.common.bean.jqgrid.JqGridPager;
import com.hanqian.kepler.common.bean.jqgrid.JqGridReturn;
import com.hanqian.kepler.common.bean.result.AjaxResult;
import com.hanqian.kepler.common.enums.BaseEnumManager;
import com.hanqian.kepler.common.jpa.specification.Rule;
import com.hanqian.kepler.core.entity.primary.core.TargetDesc;
import com.hanqian.kepler.core.entity.primary.core.TargetDescEvaluate;
import com.hanqian.kepler.core.service.core.TargetDescEvaluateService;
import com.hanqian.kepler.core.service.core.TargetDescService;
import com.hanqian.kepler.core.service.core.TargetService;
import com.hanqian.kepler.flow.entity.User;
import com.hanqian.kepler.security.annotation.CurrentUser;
import com.hanqian.kepler.web.annotation.RequestJsonParam;
import com.hanqian.kepler.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 指标描述评价
 * ============================================================================
 * author : dzw
 * createDate:  2021/1/6 。
 * ============================================================================
 */
@Controller
@RequestMapping("targetDescEvaluate")
public class TargetDescEvaluateController extends BaseController {

	@Autowired
	private TargetDescEvaluateService targetDescEvaluateService;
	@Autowired
	private TargetDescService targetDescService;
	@Autowired
	private TargetService targetService;

	/**
	 * 进入评价页面
	 */
	@GetMapping("view/{targetDescId}")
	public String view(Model model, @PathVariable String targetDescId){
		TargetDesc targetDesc = targetDescService.get(targetDescId);
		model.addAttribute("targetDesc", targetDesc);

		return "wiki/targetDesc_evaluate";
	}

	/**
	 * 发布评论
	 */
	@PostMapping("save")
	@ResponseBody
	public AjaxResult save(@CurrentUser User user, String id, String content){
		if(user == null) return AjaxResult.error("未登录");
		if(StrUtil.isBlank(id)) return AjaxResult.error("未获取到描述ID");
		if(StrUtil.isBlank(content)) return AjaxResult.error("评论内容为空");

		TargetDesc targetDesc = targetDescService.get(id);
		if(targetDesc == null) return AjaxResult.error("获取不到此指标描述");
		if(targetDesc.getVersionIndex() == null) return AjaxResult.error("未知当前指标版本");

		TargetDescEvaluate targetDescEvaluate = new TargetDescEvaluate();
		targetDescEvaluate.setCreator(user);
		targetDescEvaluate.setCreateTime(new Date());
		targetDescEvaluate.setTargetDesc(targetDesc);
		targetDescEvaluate.setVersionIndex(targetDesc.getVersionIndex());
		targetDescEvaluate.setContent(content);
		targetDescEvaluate = targetDescEvaluateService.save(targetDescEvaluate);
		return AjaxResult.successWithId("保存成功", targetDescEvaluate.getId());
	}

	/**
	 * 获取评论列表
	 */
	@RequestMapping("list")
	@ResponseBody
	public JqGridReturn list(JqGridPager pager, @RequestJsonParam("filters") JqGridFilter filters, String id, String v, String p){
		List<Rule> rules = getJqGridSearch(filters);
		Pageable pageable;
		int rows = 10;
		if(NumberUtil.isNumber(p)){
			int index = Convert.toInt(p);
			if(index < 1) index = 1;
			pageable = PageRequest.of(index-1, rows, new Sort(Sort.Direction.DESC, "createTime"));
		}else{
			pageable = getJqGridPageable(pager);
			rows = pager.getRows();
		}

		Integer versionIndex = NumberUtil.isNumber(v) ? Convert.toInt(v) : null;
		Page<TargetDescEvaluate> page = targetDescEvaluateService.findEvaluatePageByTargetDesc(targetDescService.get(id), versionIndex, pageable, rules);
		List<Map<String, Object>> dataRows = new ArrayList<>();
		page.getContent().forEach(entity -> {
			Map<String, Object> map = new HashMap<>();
			map.put("id", entity.getId());
			map.put("creatorName", entity.getCreator()!=null ? entity.getCreator().getName() : "未知");
			map.put("content", StrUtil.emptyIfNull(entity.getContent()));
			map.put("createTime", DateUtil.formatDateTime(entity.getCreateTime()));
			map.put("headerImg", entity.getCreator()!=null ? entity.getCreator().getAvatarId() : "");
			dataRows.add(map);
		});
		JqGridReturn jqGridReturn =  getJqGridReturn(dataRows, page);
		//JSONObject jsonObject = JSONUtil.parseObj(jqGridReturn);
		//jsonObject.put("surplus", jqGridReturn.getRecords() - (jqGridReturn.getPage() * rows)); //计算后面还剩多少条数据
		return jqGridReturn;
	}

	/**
	 * 删除评论
	 */
	@PostMapping("delete/{id}")
	@ResponseBody
	public AjaxResult delete(@CurrentUser User user, @PathVariable String id){
		TargetDescEvaluate targetDescEvaluate = targetDescEvaluateService.get(id);
		if(targetDescEvaluate == null) return AjaxResult.error("找不到此评论");

		targetDescEvaluate.setState(BaseEnumManager.StateEnum.Delete);
		targetDescEvaluateService.save(targetDescEvaluate);
		return AjaxResult.success();
	}

}
